package com.android.exchangeapp

import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder

fun Int.toKeyEvent() = KeyEvent(KeyEvent.ACTION_DOWN, this)

/**
 * Created by Matt on 2023/11/1.
 **/
class KeyboardAdapter(val listener: (key: KeyEvent) -> Unit) : RecyclerView.Adapter<KeyboardAdapter.KeyboardHolder>() {
    private val mKeyList = arrayOf(
        KeyEvent.KEYCODE_7.toKeyEvent(), KeyEvent.KEYCODE_8.toKeyEvent(), KeyEvent.KEYCODE_9.toKeyEvent(),
        KeyEvent.KEYCODE_4.toKeyEvent(), KeyEvent.KEYCODE_5.toKeyEvent(), KeyEvent.KEYCODE_6.toKeyEvent(),
        KeyEvent.KEYCODE_1.toKeyEvent(), KeyEvent.KEYCODE_2.toKeyEvent(), KeyEvent.KEYCODE_3.toKeyEvent(),
        KeyEvent.KEYCODE_PERIOD.toKeyEvent(), KeyEvent.KEYCODE_0.toKeyEvent(), KeyEvent.KEYCODE_CLEAR.toKeyEvent())

    class KeyboardHolder(itemView: View) : ViewHolder(itemView)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KeyboardHolder {
        return KeyboardHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_num_keyboard, parent, false)
        )
    }

    override fun getItemCount(): Int = mKeyList.size

    override fun onBindViewHolder(holder: KeyboardHolder, position: Int) {
        val itemText = holder.itemView.findViewById<TextView>(R.id.keyboard_item)
        val keyEvent = mKeyList[position]
        holder.itemView.tag = keyEvent
        holder.itemView.setOnClickListener{
            listener.invoke(it.tag as KeyEvent)
        }
        itemText.text = if (keyEvent.keyCode == KeyEvent.KEYCODE_CLEAR) "C" else keyEvent.number.toString()
    }
}